import { ref, computed, watch, onUnmounted } from 'vue'
import { debounce } from 'lodash-es'

/**
 * 实时预览组合式函数
 * @returns {Object} 实时预览功能
 */
export function useRealtimePreview() {
  const isPreviewMode = ref(false)
  const previewData = ref(null)
  const previewSettings = ref({
    autoRefresh: true,
    refreshInterval: 1000,
    showGrid: false,
    showRulers: false,
    backgroundColor: '#ffffff'
  })
  
  let refreshTimer = null

  /**
   * 切换预览模式
   */
  const togglePreview = () => {
    isPreviewMode.value = !isPreviewMode.value
    
    if (isPreviewMode.value) {
      startPreview()
    } else {
      stopPreview()
    }
  }

  /**
   * 开始预览
   */
  const startPreview = () => {
    if (previewSettings.value.autoRefresh) {
      startAutoRefresh()
    }
  }

  /**
   * 停止预览
   */
  const stopPreview = () => {
    stopAutoRefresh()
  }

  /**
   * 开始自动刷新
   */
  const startAutoRefresh = () => {
    if (refreshTimer) {
      clearInterval(refreshTimer)
    }
    
    refreshTimer = setInterval(() => {
      refreshPreview()
    }, previewSettings.value.refreshInterval)
  }

  /**
   * 停止自动刷新
   */
  const stopAutoRefresh = () => {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
  }

  /**
   * 刷新预览
   */
  const refreshPreview = debounce(() => {
    if (isPreviewMode.value) {
      // 触发预览数据更新
      updatePreviewData()
    }
  }, 300)

  /**
   * 更新预览数据
   */
  const updatePreviewData = () => {
    // 这里可以从组件状态中获取最新数据
    previewData.value = {
      timestamp: Date.now(),
      components: [], // 从实际组件状态获取
      settings: { ...previewSettings.value }
    }
  }

  /**
   * 设置预览配置
   * @param {Object} settings 预览设置
   */
  const updatePreviewSettings = (settings) => {
    previewSettings.value = { ...previewSettings.value, ...settings }
    
    if (isPreviewMode.value && settings.refreshInterval) {
      startAutoRefresh()
    }
  }

  /**
   * 生成预览URL
   * @param {Object} reportData 报表数据
   * @returns {string} 预览URL
   */
  const generatePreviewUrl = (reportData) => {
    const previewId = `preview_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    
    // 将报表数据存储到临时存储中
    sessionStorage.setItem(`preview_${previewId}`, JSON.stringify(reportData))
    
    return `${window.location.origin}/preview/${previewId}`
  }

  /**
   * 分享预览链接
   * @param {Object} reportData 报表数据
   * @returns {Promise<string>} 分享链接
   */
  const sharePreview = async (reportData) => {
    try {
      const shareData = {
        id: `share_${Date.now()}`,
        data: reportData,
        createdAt: new Date().toISOString(),
        expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString() // 7天后过期
      }
      
      // 这里可以调用API保存分享数据
      // const response = await api.createShare(shareData)
      
      // 模拟API响应
      const shareId = shareData.id
      localStorage.setItem(`share_${shareId}`, JSON.stringify(shareData))
      
      return `${window.location.origin}/share/${shareId}`
    } catch (error) {
      console.error('分享失败:', error)
      throw error
    }
  }

  /**
   * 获取分享数据
   * @param {string} shareId 分享ID
   * @returns {Object|null} 分享数据
   */
  const getSharedData = (shareId) => {
    try {
      const data = localStorage.getItem(`share_${shareId}`)
      if (!data) return null
      
      const shareData = JSON.parse(data)
      
      // 检查是否过期
      if (new Date(shareData.expiresAt) < new Date()) {
        localStorage.removeItem(`share_${shareId}`)
        return null
      }
      
      return shareData
    } catch (error) {
      console.error('获取分享数据失败:', error)
      return null
    }
  }

  // 监听器
  watch(() => previewSettings.value.autoRefresh, (newValue) => {
    if (isPreviewMode.value) {
      if (newValue) {
        startAutoRefresh()
      } else {
        stopAutoRefresh()
      }
    }
  })

  // 清理
  onUnmounted(() => {
    stopAutoRefresh()
  })

  return {
    // 状态
    isPreviewMode,
    previewData,
    previewSettings,
    
    // 方法
    togglePreview,
    startPreview,
    stopPreview,
    refreshPreview,
    updatePreviewSettings,
    generatePreviewUrl,
    sharePreview,
    getSharedData
  }
}

/**
 * 协作功能组合式函数
 * @returns {Object} 协作功能
 */
export function useCollaboration() {
  const isConnected = ref(false)
  const collaborators = ref([])
  const cursors = ref(new Map())
  const comments = ref([])
  const changes = ref([])
  
  let websocket = null
  let heartbeatTimer = null

  /**
   * 连接协作服务
   * @param {string} roomId 房间ID
   * @param {Object} user 用户信息
   */
  const connect = async (roomId, user) => {
    try {
      // 这里应该连接到实际的WebSocket服务
      // websocket = new WebSocket(`ws://localhost:3001/collaboration/${roomId}`)
      
      // 模拟连接
      isConnected.value = true
      
      // 模拟其他协作者
      collaborators.value = [
        {
          id: 'user1',
          name: '张三',
          avatar: '',
          color: '#409EFF',
          cursor: { x: 0, y: 0 },
          lastSeen: Date.now()
        },
        {
          id: 'user2', 
          name: '李四',
          avatar: '',
          color: '#67C23A',
          cursor: { x: 100, y: 100 },
          lastSeen: Date.now()
        }
      ]
      
      startHeartbeat()
      
    } catch (error) {
      console.error('连接协作服务失败:', error)
      throw error
    }
  }

  /**
   * 断开连接
   */
  const disconnect = () => {
    if (websocket) {
      websocket.close()
      websocket = null
    }
    
    stopHeartbeat()
    isConnected.value = false
    collaborators.value = []
    cursors.value.clear()
  }

  /**
   * 发送变更
   * @param {Object} change 变更数据
   */
  const sendChange = (change) => {
    if (!isConnected.value) return
    
    const changeData = {
      type: 'change',
      id: `change_${Date.now()}`,
      timestamp: Date.now(),
      change
    }
    
    // 发送到WebSocket
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      websocket.send(JSON.stringify(changeData))
    }
    
    // 添加到本地变更历史
    changes.value.unshift(changeData)
    
    // 限制历史记录数量
    if (changes.value.length > 100) {
      changes.value = changes.value.slice(0, 100)
    }
  }

  /**
   * 发送光标位置
   * @param {Object} position 光标位置
   */
  const sendCursor = debounce((position) => {
    if (!isConnected.value) return
    
    const cursorData = {
      type: 'cursor',
      position,
      timestamp: Date.now()
    }
    
    if (websocket && websocket.readyState === WebSocket.OPEN) {
      websocket.send(JSON.stringify(cursorData))
    }
  }, 100)

  /**
   * 添加评论
   * @param {Object} comment 评论数据
   */
  const addComment = (comment) => {
    const commentData = {
      id: `comment_${Date.now()}`,
      ...comment,
      timestamp: Date.now()
    }
    
    comments.value.push(commentData)
    
    // 发送到协作服务
    sendChange({
      type: 'comment-add',
      data: commentData
    })
    
    return commentData
  }

  /**
   * 删除评论
   * @param {string} commentId 评论ID
   */
  const removeComment = (commentId) => {
    const index = comments.value.findIndex(c => c.id === commentId)
    if (index > -1) {
      comments.value.splice(index, 1)
      
      sendChange({
        type: 'comment-remove',
        data: { commentId }
      })
    }
  }

  /**
   * 获取在线协作者
   */
  const getOnlineCollaborators = computed(() => {
    const now = Date.now()
    return collaborators.value.filter(user => 
      now - user.lastSeen < 30000 // 30秒内活跃
    )
  })

  /**
   * 开始心跳
   */
  const startHeartbeat = () => {
    heartbeatTimer = setInterval(() => {
      if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify({ type: 'heartbeat' }))
      }
    }, 10000) // 每10秒发送心跳
  }

  /**
   * 停止心跳
   */
  const stopHeartbeat = () => {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer)
      heartbeatTimer = null
    }
  }

  /**
   * 处理接收到的消息
   * @param {Object} message 消息数据
   */
  const handleMessage = (message) => {
    switch (message.type) {
      case 'change':
        handleRemoteChange(message.change)
        break
      case 'cursor':
        handleRemoteCursor(message.userId, message.position)
        break
      case 'user-join':
        handleUserJoin(message.user)
        break
      case 'user-leave':
        handleUserLeave(message.userId)
        break
      case 'comment':
        handleRemoteComment(message.comment)
        break
    }
  }

  /**
   * 处理远程变更
   * @param {Object} change 变更数据
   */
  const handleRemoteChange = (change) => {
    // 应用远程变更到本地状态
    changes.value.unshift({
      id: `remote_${Date.now()}`,
      timestamp: Date.now(),
      change,
      remote: true
    })
  }

  /**
   * 处理远程光标
   * @param {string} userId 用户ID
   * @param {Object} position 光标位置
   */
  const handleRemoteCursor = (userId, position) => {
    cursors.value.set(userId, {
      position,
      timestamp: Date.now()
    })
    
    // 更新协作者信息
    const collaborator = collaborators.value.find(c => c.id === userId)
    if (collaborator) {
      collaborator.cursor = position
      collaborator.lastSeen = Date.now()
    }
  }

  /**
   * 处理用户加入
   * @param {Object} user 用户信息
   */
  const handleUserJoin = (user) => {
    const existing = collaborators.value.find(c => c.id === user.id)
    if (!existing) {
      collaborators.value.push(user)
    }
  }

  /**
   * 处理用户离开
   * @param {string} userId 用户ID
   */
  const handleUserLeave = (userId) => {
    const index = collaborators.value.findIndex(c => c.id === userId)
    if (index > -1) {
      collaborators.value.splice(index, 1)
    }
    cursors.value.delete(userId)
  }

  /**
   * 处理远程评论
   * @param {Object} comment 评论数据
   */
  const handleRemoteComment = (comment) => {
    if (comment.action === 'add') {
      comments.value.push(comment.data)
    } else if (comment.action === 'remove') {
      const index = comments.value.findIndex(c => c.id === comment.data.commentId)
      if (index > -1) {
        comments.value.splice(index, 1)
      }
    }
  }

  // 清理
  onUnmounted(() => {
    disconnect()
  })

  return {
    // 状态
    isConnected,
    collaborators,
    cursors,
    comments,
    changes,
    
    // 计算属性
    getOnlineCollaborators,
    
    // 方法
    connect,
    disconnect,
    sendChange,
    sendCursor,
    addComment,
    removeComment,
    handleMessage
  }
}



